/**
 * @FileName: MyJdbcAuthzService.java
 * @Author
 * @Description:
 * @Date 2015年12月21日 下午2:20:19
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.security;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import cn.dreampie.shiro.core.JdbcAuthzService;
import cn.dreampie.shiro.core.handler.AuthzHandler;
import cn.dreampie.shiro.core.handler.JdbcPermissionAuthzHandler;
import cn.hpclub.server.model.Permission;

public class MyJdbcAuthzService implements JdbcAuthzService{

    @Override
    public Map<String, AuthzHandler> getJdbcAuthz(){
        // 加载数据库的url配置
        // 按长度倒序排列url
        Map<String, AuthzHandler> authzJdbcMaps = Collections
                .synchronizedMap(new TreeMap<String, AuthzHandler>(new Comparator<String>(){
                    public int compare(String k1, String k2){
                        int result = k2.length() - k1.length();
                        if(result == 0){
                            return k1.compareTo(k2);
                        }
                        return result;
                    }
                }));
        // 遍历角色
        List<Permission> permissions = null;
        permissions = Permission.dao.getAllPermission();
        // 遍历权限
        for(Permission permission : permissions){
            // 权限可用
            if(!isEmpty(permission.getStr("url")) && !isEmpty(permission.getStr("permission"))){
                // System.out
                // .println("url:" + permission.getStr("url") + ",permission:" +
                // permission.getStr("permission"));
                authzJdbcMaps.put(permission.getStr("url"),
                                  new JdbcPermissionAuthzHandler(permission.getStr("permission")));
            }
        }
        return authzJdbcMaps;
    }

    private boolean isEmpty(String content){
        return content == null || content.length() == 0;
    }
}
